import json
import re
# 导入用户模型类进行用户表查询
from django_redis import get_redis_connection

from django.shortcuts import render
from django import http
from django.http import HttpResponse, JsonResponse
from django.views import View
from user.models import User


# Create your views here.
class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        '''判断用户名是否重复'''
        # 1.查询username在数据库中的个数
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '访问数据库失败'})

        # 2.返回结果(json) ---> code & errmsg & count
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': count})


class MobileCountView(View):

    def get(self, request, mobile):
        '''判断手机号是否重复注册'''
        # 1.查询mobile在mysql中的个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '查询数据库出错'})

        # 2.返回结果(json)
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': count})


class RegisterView(View):
    def post(self, request):
        # 获取前端json数据
        data = request.body.decode()
        #  将json数据转成字典
        data_dict = json.loads(data)
        # 1.获取前段各项数据
        username = data_dict.get('username')  # 用户名
        password = data_dict.get('password')  # 密码
        password2 = data_dict.get('password2')  # 确认密码
        mobile = data_dict.get('mobile')  # 手机号
        sms_code = data_dict.get('sms_code')  # 短信验证码
        allow = data_dict.get('allow')  # 是否同意用户协议
        # 2.验证数据
        #  验证数据完整性
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"errmsg": "数据错误"}, status=400)
        #  验证两次密码是都一致
        if password != password2:
            return JsonResponse({"errmsg": "数据错误"}, status=400)
        # 验证短信验证是否一样,查询redis进行对比

        # 创建redis链接对象
        conn_sms = get_redis_connection('sms_code')
        # 查询redis数据库获取发送的短信验证码
        real_sms = conn_sms.get('sms_code_%s' % mobile)
        # 对查询数据解码  转换成字符串
        real_sms_str = real_sms.decode()
        # 判断短信 转换字母成小写
        if sms_code != real_sms_str:
            return JsonResponse({"errmsg": "数据错误"}, status=400)
        # 验证手机号码格式
        if not re.match('1[3-9]\d{9}', mobile):
            return JsonResponse({"errmsg": "数据错误"}, status=400)
        # 验证用户名长度
        if not re.match('[\w-]{5,20}', username):
            return JsonResponse({"errmsg": "数据错误"}, status=400)
        # 3.保存数据到数据库
        # 导入用户表进行保存
        User.objects.create_user(username=username, password=password, mobile=mobile)
        return JsonResponse({'msg': 'ok'})
